AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')

function ENT:Initialize()
	self.BaseClass.Initialize(self)

	self.Drugs = {}
end

function ENT:Use(ply, caller)
	if (self.LastUsed + 0.5 > CurTime()) then
		self.LastUsed = CurTime()
	else
		if (ply==self.dt.Owner || IsAllied(ply, self.dt.Owner) || !self.Locked) then
			if (ply==self.dt.Owner) then
				self.Locked = true
			end
			self:TransmitDrugs(ply)
		else
			Notify(ply,4,3,"This Pill Box is locked! Use a lock pick to force it open.")
		end
		self.LastUsed = CurTime()
	end
end

function ccWithdrawDrug(ply, cmd, args)
	local pillbox = ents.GetByIndex(args[1])
	local drugindex = tonumber(args[2])
	local drugid = tonumber(args[3])
	
	if pillbox then
		if (ply!=pillbox.dt.Owner && !IsAllied(ply, pillbox.dt.Owner) && pillbox.Locked) then return end
		if pillbox:GetPos():Distance(ply:GetPos()) < 110 then
			if pillbox.Drugs[drugindex] then
				pillbox:MakeDrug(drugid)
				pillbox:WithdrawDrug(drugindex)
				pillbox:TransmitDrugs(ply)
			end
		else
			ply:ChatPrint("You are too far away to withdraw drugs.")
		end
	end
end
concommand.Add("pillboxwithdraw", ccWithdrawDrug)

function ENT:StartTouch(ent)
	local druglist = GetDrugList()
	if(table.Count(self.Drugs) >= self.MaxDrugs) then return end
	if ent.Base == "base_drug" then
		for k, ClassName in pairs(druglist) do
			if ClassName == ent.ClassName then
				self:DepositDrug(k)
				ent:Remove()
				break
			end
		end
	end
end

function ENT:TransmitDrugs(ply)
	umsg.Start("pillboxmenu", ply)
		umsg.String(glon.encode(self.Drugs))
		umsg.Short(self:EntIndex())
	umsg.End()
end

function ENT:DepositDrug(drugid)
	table.insert(self.Drugs, drugid)
end

function ENT:WithdrawDrug(index)
	table.remove(self.Drugs, index)
end

function ENT:MakeDrug(drugid)
	local druglist = GetDrugList()
	
	local drug = ents.Create(druglist[drugid])
		drug:SetPos(self:GetPos() + Vector(40, 0, -10))
	drug:Spawn()
end

function ENT:OnRemove()
	for k, id in pairs(self.Drugs) do
		self:MakeDrug(id)
	end
end

function ENT:SetUnlocked()
	self.Locked = false
end